import {
  shallowRef,
  onUnmounted,
  reactive,
  h,
  createVNode,
  render,
  onMounted,
  getCurrentInstance,
} from 'vue';
// import { getAppContext } from '@/store';

export interface EditModalProps {
  component?: any;
  onSuccess?: () => void;
}

function getAppContext() {}

export function useEditModalExtra(props: EditModalProps = {}) {
  const { onSuccess, component } = props;

  const modalRef = shallowRef();

  const appContext = getCurrentInstance();

  const containerRef = shallowRef<HTMLDivElement>();

  // const openLoading = ref(false);

  function setRef(el: any) {
    modalRef.value = el;
  }

  onUnmounted(() => {
    modalRef.value = null;
  });

  function returnVerifyRef(method: (instance: any) => Promise<any>) {
    if (modalRef.value) {
      return method(modalRef.value);
    }
    return Promise.reject(new Error('弹窗modalRef为null'));
  }

  function showModal(type: string, record?: any) {
    return returnVerifyRef((r) => {
      return r.showModal(type, record);
    });
  }

  function showEdit(record: any) {
    return showModal('edit', record);
  }

  function showAdd(record?: any) {
    return showModal('add', record);
  }

  function showDetail(record?: any) {
    return showModal('detail', record);
  }

  function onModalSuccess() {
    if (onSuccess) onSuccess();
  }

  function renderModal() {
    const context = appContext?.appContext || getAppContext();

    const vnode = createVNode(component, {
      onSuccess: onModalSuccess,
    });

    // @ts-ignore
    vnode.appContext = context;

    // console.log('appContext', appContext);

    const container = document.createElement('div');
    document.body.appendChild(container);
    // 进行渲染
    render(vnode, container);

    // @ts-ignore
    setRef(vnode.component.exposed);

    // console.log('vnode', vnode);

    containerRef.value = container;
  }

  onMounted(() => {
    renderModal();
  });

  onUnmounted(() => {
    const container = containerRef.value;
    if (container) {
      render(null, container);
      // 获取包含要删除的div元素的父元素
      const parentElement = container.parentElement!;
      // 从父元素中删除该div元素
      parentElement.removeChild(container);
    }
  });

  return reactive({
    ref: setRef,
    onSuccess: onModalSuccess,
    showEdit,
    showAdd,
    showModal,
    showDetail,
    renderModal,
  });
}
